const { SuccessModel, ErrorModel } = require("../model/resModel");
const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
} = require("../controller/blog");

const handleBlogRouter = (req, res) => {
  const method = req.method;
  const id = req.query.id;

  if (method === "GET" && req.path === "/api/blog/list") {
    const author = req.query.author || "";
    const keyword = req.query.keyword || "";

    const result = getList(author, keyword);
    return result.then((listData) => {
      return new SuccessModel(listData);
    });
  }
  if (method === "GET" && req.path === "/api/blog/detail") {
    // const data = getDetail(id);
    // return new SuccessModel(data);
    const result = getDetail(id);
    return result.then(data=>{
      return new SuccessModel(data);
    })
  }

  // 新建一篇博客
  if (method === "POST" && req.path === "/api/blog/new") {
    // let data = newBlog(req.body);
    // return new SuccessModel(data);

    req.body.author = 'wangerma'; // 假数据
    const result = newBlog(req.body);
    return result.then(data=>{
      return new SuccessModel(data);
    })
  }

  if (method === "POST" && req.path === "/api/blog/update") {
    let result = updateBlog(id, req.body);
    return result.then(val=>{
      if (val) {
        return new SuccessModel();
      } else {
        return new ErrorModel("更新博客失败");
      }
    })

  }
  if (method === "POST" && req.path === "/api/blog/del") {
    let author = 'wangerma'; // 假数据
    let result = delBlog(id, author);
    return result.then(val=>{
      if (val) {
        return new SuccessModel();
      } else {
        return new ErrorModel("删除博客失败");
      }
    })
  }
};
module.exports = handleBlogRouter;
